<?php
require_once 'Zend/Acl.php';
require_once 'Zend/Acl/Role.php';
require_once 'Zend/Acl/Resource.php';
require_once 'Zend/Session/Namespace.php';
require_once 'RolesProvider.class.php';
require_once 'ResourcesProvider.class.php';

class Gea_Zend_Acl_Factory {
	public static function getInstance($dbAdapter = null) {
		$zaclbNamespace = new Zend_Session_Namespace('Gea_Zend_Acl_Factory');
		if (!isset ($zaclbNamespace->zend_acl)) {
			if (!isset ($dbAdapter)) {
				throw new Exception('La primera vez que se crea Zend_Acl es necesario obtener el dbAdapter');
			}
			$zend_acl = new Zend_Acl();

			/**
			 * Asignamos roles
			 */

			$result = RolesProvider :: getRolesPairs();
			foreach ($result as $key => $value) {
				$zend_acl->addRole(new Zend_Acl_Role($key));
			}
			/**
			* Asignamos recursos
			*/

			$result = ResourcesProvider :: getResourcesPairs();
			foreach ($result as $key => $value) {
				$zend_acl->add(new Zend_Acl_Resource($value));
			}

			/**
			 *	Asignamos permisos
			 */

			$result = $dbAdapter->fetchAll('SELECT ROL_ID,RESOURCE_NOMBRE FROM ROL_HAS_RESOURCE');
			foreach ($result as $value) {
				$zend_acl->allow($value['ROL_ID'], $value['RESOURCE_NOMBRE']);
			}
			$zaclbNamespace->zend_acl = $zend_acl;
		} else {
			return $zaclbNamespace->zend_acl;
		}
	}
}
?>